package com.wwdeng.print.app.printer;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 从本地路径获取bitmap
 */
public class BitmapLoader {

    /**
     * 从本地路径加载Bitmap
     * @param filePath 图片文件路径
     * @return 加载成功的Bitmap，失败返回null
     */
    public static Bitmap loadBitmap(String filePath) {
        return loadBitmap(filePath, -1, -1);
    }

    /**
     * 从本地路径加载Bitmap，并指定最大宽高
     * @param filePath 图片文件路径
     * @param reqWidth 要求的最大宽度，-1表示不限制
     * @param reqHeight 要求的最大高度，-1表示不限制
     * @return 加载成功的Bitmap，失败返回null
     */
    public static Bitmap loadBitmap(String filePath, int reqWidth, int reqHeight) {
        FileInputStream fis = null;
        try {
            //检查文件是否存在
            File file = new File(filePath);
            if (!file.exists()) {
                Log.e("TAG", "File not found: " + filePath);
                return null;
            }

            //解码只获取图片尺寸
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            fis = new FileInputStream(file);
            BitmapFactory.decodeStream(fis, null, options);
            try {
                fis.close();
            } catch (IOException e) {
                Log.e("TAG", "Close stream error", e);
            }

            //计算采样率
            options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
            options.inJustDecodeBounds = false;

            //重新加载图片
            fis = new FileInputStream(file);
            Bitmap bitmap = BitmapFactory.decodeStream(fis, null, options);

            if (bitmap == null) {
                Log.e("TAG", "Decode bitmap failed: " + filePath);
                return null;
            }
            return bitmap;
        } catch (Exception e) {
            Log.e("TAG", "Load bitmap error: " + filePath, e);
            return null;
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    Log.e("TAG", "Close stream error", e);
                }
            }
        }
    }

    /**
     * 计算采样率
     */
    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        if (reqWidth <= 0 || reqHeight <= 0) {
            return 1;
        }
        // 原始图片尺寸
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;
            // 计算最大的inSampleSize值，该值是2的幂，
            // 并保持高度和宽度大于请求的高度和宽度
            while ((halfHeight / inSampleSize) >= reqHeight
                    && (halfWidth / inSampleSize) >= reqWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }

    /**
     * 安全回收Bitmap
     */
    public static void recycleBitmap(Bitmap bitmap) {
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
        }
    }
}
